from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import template
from google.appengine.api import channel
from django.utils import simplejson
from src.util import *
import datetime


class ChannelPage(webapp.RequestHandler):
    def make_client_id(self, client_name):
        return client_name + datetime.datetime.today().strftime('%Y%m%d%H%M%S')
    
    def add_cookie(self, name, value):
        self.response.headers.add_header('Set-Cookie' , '%s=%s' % (name, value))
    
    def remove_cookie(self, name):
        self.response.headers.add_header('Set-Cookie' , '%s=0; expires=%s' % (name, (datetime.datetime.today() - datetime.timedelta(days=3)).strftime('%a, %d-%b-%Y %H:%M:%S GMT')))
    
    def save_data_to_client(self):
        chatter_name = self.request.get('chatter-name')
        if chatter_name:
            client_id = self.make_client_id(chatter_name)
            c = ChatClient(clientId=client_id)
            c.put()
            self.add_cookie('chatter-name', chatter_name)
            self.add_cookie('client-id', client_id)
            self.add_cookie('object-key', str(c.key()))
    
    def clear_data_in_client(self):
        id = self.get_object_key_from_client()
        
        if id:            
            c = ChatClient.get(db.Key(id))
            c.delete()
        
        self.remove_cookie('chatter-name')
        self.remove_cookie('client-id')
        self.remove_cookie('object-key')
    
    def get_object_key_from_client(self):
        object_key = None
        if self.request.cookies.has_key('object-key'):
            object_key = self.request.cookies['object-key']
        
        return object_key
    
    def get_chatter_name_from_client(self):
        chatter_name = None
        if self.request.cookies.has_key('chatter-name'):
            chatter_name = str(self.request.cookies['chatter-name'])
        
        return chatter_name
    
    def get_client_id_from_client(self):
        client_id = None
        if self.request.cookies.has_key('client-id'):
            client_id = str(self.request.cookies['client-id'])
        
        return client_id
    
    def post(self):
        action = self.request.get('action')
        if action == 'leave':
            self.clear_data_in_client()
        else:
            self.save_data_to_client()
            
        self.redirect('/channel')
    
    def get(self):
        template_values = {
            'page': { 'title': 'Chatroom' , 'name' : 'channel' }
        }

        client_id = self.get_client_id_from_client()
        if client_id:
            template_values['client_token'] = channel.create_channel(client_id)  
            
        chatter_name = self.get_chatter_name_from_client()
        if chatter_name:
            template_values['chatter_name'] = chatter_name 

        self.response.out.write(template.render(get_absolute_path('templates/channel.htm'), template_values))
    

class ChannelMessageHandler(webapp.RequestHandler):
    
    def get_chat_message(self):
        # The gameUpdate object is sent to the client to render the state of a game.
        chatUpdate = {
          'sender': self.request.get('sender'),
          'message': self.request.get('text_chat'),
          'isCommand' : self.request.get('msg_type') == 'command',
          'commandText' : self.request.get('command_message')
        }
        
        return simplejson.dumps(chatUpdate)

    def post(self):
        for c in ChatClient.all():
            channel.send_message(c.clientId, self.get_chat_message())


class ChatClient(db.Model):
    clientId = db.StringProperty()
